/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.web.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.jfinal.handler.Handler;
import com.jfinal.log.Log;
import com.jfinal.render.Render;
import com.jfinal.render.RenderManager;
import com.lambkit.core.task.http.HttpWorkCenter;
import com.lambkit.JFLambkit;
import com.lambkit.servlet.NewCookie;
import com.lambkit.node.LambkitNodeManager;
import com.lambkit.servlet.LambkitServletContext;
import com.lambkit.web.HttpDispatcher;
import com.lambkit.web.LambkitControllerContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LambkitHandler extends Handler {
    static Log log = Log.getLog(LambkitHandler.class);

    private HttpDispatcher httpDispatcher;

    public LambkitHandler() {
        httpDispatcher = new HttpDispatcher();
        httpDispatcher.init(JFLambkit.getApp().context().getWorkCenter(HttpWorkCenter.class));
    }
    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        if (target.indexOf('.') != -1 && !target.startsWith("/lambkit/lms/druid")) {
            return;
        }
        TimeInterval timer = DateUtil.timer();
        boolean flag = httpDispatcher.start(new LambkitServletContext(request, response));
        if(flag) {
            isHandled[0] = true;
            System.out.println("Api of {" + target + "} use time：" + timer.interval() + "ms\n");
            return;
        }

        /**
         * 执行请求逻辑
         */
        //System.out.println("handler first....");
        doHandle(target, request, response, isHandled);

        //每个链接都确定来自那个node节点
        NewCookie cookie = new NewCookie("lambkit", LambkitNodeManager.me().getNode().getId());
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        cookie.setSameSite("strict");
        response.addHeader(NewCookie.SET_COOKIE, cookie.toString());
        httpDispatcher.stop();
        if(target.indexOf('.')==-1) {
            System.out.println("Api of [" + target + "] use time：" + timer.interval() + "ms\n");
        }
    }

    private void doHandle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        //request.setAttribute("REQUEST", request);
        //request.setAttribute("CPATH", request.getContextPath());
        //request.setAttribute("host", request.getLocalPort());
        next.handle(target, request, response, isHandled);
    }


    /**
     * 统一异常处理, 未完成
     * @param exception
     */
    public void exceptionHandler(Exception exception, HttpServletRequest request, HttpServletResponse response) {
        log.error("统一异常处理：", exception);
        request.setAttribute("ex", exception);
        if (null != request.getHeader("X-Requested-With") && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
            request.setAttribute("requestHeader", "ajax");
        }
        Render render = null;
//        if (exception instanceof UnauthorizedException) {
//            // shiro没有权限异常
//            render = RenderManager.me().getRenderFactory().getErrorRender(403);
//            if(render==null) {
//                render = new Render() {
//                    @Override
//                    public void render() {
//                       this.response.setStatus(403);
//                    }
//                };
//            }
//        } else if (exception instanceof InvalidSessionException) {
//            // shiro会话已过期异常
//            render = RenderManager.me().getRenderFactory().getRender("/lambkit/error/error.html");
//        } else {
            render = RenderManager.me().getRenderFactory().getRender("/lambkit/error/error.html");
//        }
        if(render!=null) {
            render.setContext(request, response);
            render.render();
        }
    }

}
